package product

import (
	"context"
	"group-buy/group_buy/internal/models"

	"group-buy/group_buy/internal/svc"
	"group-buy/group_buy/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListProductLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListProductLogic {
	return &ListProductLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListProductLogic) ListProduct(req *types.ListProductReq) (resp *types.ListProductRsp, err error) {
	data := make([]*models.Product, 0)
	sql := l.svcCtx.Engine.Where("")
	if req.BusinessId > 0 {
		sql = sql.And("business_id=? or business_id=1", req.BusinessId)
	} else {
		sql = sql.And("business_id=1")
	}
	if req.Status > 0 {
		sql = sql.And("status=?", req.Status)
	}
	count, err := sql.OrderBy("sort").Limit(req.Size, (req.Page-1)*req.Size).FindAndCount(&data)
	if err != nil {
		return nil, err
	}
	list := make([]*types.Product, len(data), len(data))
	for i, _ := range data {
		list[i] = &types.Product{
			Id:             data[i].Id,
			Name:           data[i].Name,
			Price:          data[i].Price,
			Unit:           data[i].Unit,
			Cover:          data[i].Cover,
			Detail:         data[i].Detail,
			BusinessId:     data[i].BusinessId,
			WriteOff:       data[i].WriteOff,
			Status:         data[i].Status,
			WriteOffUserId: data[i].WriteOffUserId,
			Sort:           data[i].Sort,
		}
	}

	return &types.ListProductRsp{
		List:  list,
		Count: count,
	}, nil
}
